<?php
/*
	[LocoySpider] (C)2005-2010 Lewell Inc.
	火车采集器 Discuz-x 1.0  UTF-8 帖子发布接口
	最后更新:2010.06.23 by RQ204
*/

/********密码验证***********/
$password='1';				                   //这个密码是登陆验证用的.您需要在模块里设置和这里一样的密码....注意一定需要修改.
if($password!=$_GET['pw']) exit('验证密码错误');   //安全检测,密码不符则退出


/******随机回复用户名设置,用户可自行修改******/
$replyers="";
$rep="";                     				   //随机回复的用户名,为空的话则不使用,多个用户名之间用 , 分开,如 $replyers="'admin2','admin3'";  


/******以下代码加载并设置数据库配置,非专业人员不建议修改********/
include('config/config_global.php');					//加载数据库配置
$dbhost=$_config['db']['1']['dbhost'];
$dbuser=$_config['db']['1']['dbuser'];
$dbpw=$_config['db']['1']['dbpw'];
$dbname=$_config['db']['1']['dbname'] ;
$tablepre=$_config['db']['1']['tablepre'];
$dbcharset = 'utf8';			                       // MySQL 字符集, 可选 'gbk', 'big5', 'utf8', 'latin1', 留空为按照论坛字符集设定
$charset = 'utf8';			                       // 论坛页面默认字符集, 可选 'gbk', 'big5', 'utf-8'


/****以下代码对数据进行安全过滤,非专业人员不建议修改***************/
set_magic_quotes_runtime(0);
define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
$timestamp=time()-86400;

if(PHP_VERSION < '4.1.0') {
	$_GET = &$HTTP_GET_VARS;
	$_POST = &$HTTP_POST_VARS;
	$_COOKIE = &$HTTP_COOKIE_VARS;
	$_SERVER = &$HTTP_SERVER_VARS;
	$_ENV = &$HTTP_ENV_VARS;
	$_FILES = &$HTTP_POST_FILES;
}

if (isset($_REQUEST['GLOBALS']) OR isset($_FILES['GLOBALS'])) {
	exit('Request tainting attempted.');
}

foreach(array('_COOKIE', '_POST', '_GET') as $_request) {
	foreach($$_request as $_key => $_value) {
		$_key{0} != '_' && $$_key = daddslashes($_value);
	}
}

if (!MAGIC_QUOTES_GPC && $_FILES) {
	$_FILES = daddslashes($_FILES);
}

/*****************以下是核心的处理代码******************/


$db=new db($dbhost,$dbuser,$dbpw,$dbname,$charset,$dbcharset);//创建数据库链接

$cates=$db->get_array("Select fid as cid,fup as pid,name as cname,type from {$tablepre}forum_forum where  status=1 order by displayorder");//先获取分类信息

if($_POST){
	extract($_POST,EXTR_OVERWRITE);//获取POST过来的参数
	if(!$title){
		exit('标题不能为空');
	}
	if(!$content){
	$content=$title;
	}
	if(!$cid){
		exit('栏目不能为空');
	}
	if(!$username){
		exit('用户名不能为空');
	}
	//判断该主题是否有附件
	if($attachment)
	{
		$isattachment=1;
	}else
	     {
		 $isattachment=0;
	     }
	foreach ($cates as $f=>$v)
	{
		if($v['cid']==$cid)
		{		
			$eid=$v;
			$cname=$v['cname'];
			if($v['type']=='group') exit("该栏目不能发布内容"); 
		}
	}
	if(!$eid) exit("不存在的版块id:$cid");
  //去掉采集为空的回复
  $rep="<br/>".$rep;
while(strpos($rep,'||||||'))
	{
	echo "true";
	$rep=str_replace("||||||","|||",$rep);
	}
	$rep=str_replace("<br/>","",$rep);
	$content=implode('|||',array($content,$rep,));
	$replys=array($content);
	if(strpos($content,'|||')>0)
	{
		$replys=explode('|||',$content);
		$content=$replys[0];
		//unset($replys[0]);
	}

	/***以上为数据检测及赋值**/	
	$userinfo=$db->fetch_first("Select uid as uid from {$tablepre}common_member where username='商务活动'");
	if(!$userinfo) exit("不存在用户$username");
	$uid=$userinfo['uid'];
	$hits=mt_rand(0,20);
	//先处理主题（字段special=4是标识这个主题是活动）
	if($city)
	{
	$title=$title;
	}
	$sql="INSERT INTO {$tablepre}forum_thread (fid, posttableid, readperm, price, typeid, sortid, author, authorid, subject, dateline, lastpost, lastposter, displayorder, digest, special, attachment, moderated, status, isgroup)VALUES ('$cid', '', '0', '0', '$typeid', '0', '$username', '$uid', '$title', '$timestamp', '$timestamp', '$username', '0', '0', '4', '2', '0', '0', '0')";
	$db->query($sql);
	$tid=$db->insert_id();
	$db->query("UPDATE  {$tablepre}common_member_field_home SET `recentnote`='$title' WHERE `uid`='$uid'");
	//在表pre_forum_activity中添加记录
	
	//主题回复这块是一样的
	if($replyers)
	{
		$sql="Select `uid`, `username` from {$tablepre}common_member where username in ($replyers)";
		$result=$db->get_array($sql);
	}
	$replycount=-1;
	$first=1;
	foreach($replys as $content)
	{
if(!empty($content))
  {
		$db->query("INSERT INTO {$tablepre}forum_post_tableid SET `pid`=''");
		$pid=$db->insert_id();
		//处理帖子内容，涉及的表为forum_post
		$db->query("INSERT INTO {$tablepre}forum_post SET `fid`='$cid',`tid`='$tid',`first`='$first',`author`='$username',`authorid`='$uid',`subject`='$title',`dateline`='$timestamp',`message`='$content',`useip`='',`invisible`='0',`anonymous`='0',`usesig`='1',`htmlon`='1',`bbcodeoff`='0',`smileyoff`='-1',`parseurloff`='',`attachment`='2',`tags`='$tags',`pid`='$pid'");
		//处理主题附件
	if($isattachment)
	{
	//换算附件大小
	$filesize="";
	if(strpos('M', $filesize))
	  {
	$filesizenum=intval($filesize);
	$filesize=$filesizenum*1024*1024;
	  }else
	  {
	  $filesizenum=intval($filesize);
	  $filesize=$filesizenum*1024;
	  }
	  //附件分表以后，一般是用函数根据tid来确定tableid
$tableid=getattachtableid($tid);
$db->query("INSERT INTO {$tablepre}forum_attachment (tid, pid, uid, tableid,downloads)VALUES ('$tid', '$pid', '$uid', '$tableid', '0')");
	$aid=$db->insert_id();
$db->query("INSERT INTO {$tablepre}forum_threadimage (tid, attachment, remote)VALUES ('$tid', '$attachment', '0')");
$sql="INSERT INTO {$tablepre}forum_attachment_";
	$sql=$sql.$tableid."(aid,tid,pid,uid,dateline,filename,filesize,attachment,remote,description,readperm,price,isimage,width,thumb,picid)VALUES ('$aid','$tid',	'$pid','$uid','$timestamp','','0','$attachment','0','','0','0','1','280','0','0')";
	$db->query($sql);
			//在表pre_forum_activity中添加记录,添加一个活动
			//先得把英文时间格式转换一下
			$starttimefrom=strtotime($starttimefrom);
			$starttimeto=strtotime($starttimeto);
			$expiration=strtotime($expiration);
	$sql="INSERT INTO {$tablepre}forum_activity (`tid`,	`uid`,	`aid`,	`cost`,	`starttimefrom`,	`starttimeto`,	`place`,	`class`,	`gender`,	`number`,	`applynumber`,	`expiration`,	`ufield`,	`credit`,	`organizer`,	`undertakingside`,	`costtext`,	`scale`,	`city`,	`crowd`,	`jiontips`,	`web`,	`contact`,	`phone`,	`fax`,	`email`,	`contactlist`,	`theme`,	`guests`,	`background`,	`coorganizer`,	`industry`
)VALUES ('$tid',	'$uid',	'$aid',	'',	'$starttimefrom',	'$starttimeto',	'$place',	'$class',	'',	'',	'',	'$expiration',	'',	'',	'$organizer',	'$undertakingside',	'$costtext',	'$scale',	'$city',	'$crowd',	'',	'$web',	'$contact',	'$phone',	'$fax',	'$email',	'',	'$theme',	'',	'$background',	'$coorganizer',	'$industry'
)";
	$db->query($sql);
	}
		$db->query("REPLACE INTO {$tablepre}common_syscache (cname, ctype, dateline, data) VALUES ('max_post_id', '0', '$timestamp', '$pid')");
		$db->query("UPDATE {$tablepre}common_member_count SET extcredits1=extcredits1+'0',extcredits2=extcredits2+'2',extcredits3=extcredits3+'0',threads=threads+'1',posts=posts+'1' WHERE uid IN ('$uid')");
		$db->query("UPDATE {$tablepre}common_credit_rule_log SET cyclenum=cyclenum+1,total=total+1,dateline='$timestamp',extcredits1='0',extcredits2='2',extcredits3='0' WHERE clid='2'");
		$db->query("UPDATE  {$tablepre}common_member SET `credits`=`credits`+1 WHERE `uid`='$uid'");
		$db->query("UPDATE {$tablepre}common_member_status SET lastpost='$timestamp' WHERE uid IN ('$uid')");
		
		if(count($replys)>1)
		{		
			if($result)
			{
				$rnd=array_rand($result);
				$uid=$result[$rnd]['uid'];
				$username=$result[$rnd]['username'];
			}
			$timestamp+=rand();
			$title='';
		}
		$first=0;
		$isattachment=0;
		$replycount++;
	}
	else
	{
	}
	}
//更新版块的主题数、帖子数、今日帖子数
	$db->query("UPDATE {$tablepre}forum_forum SET lastpost='$tid	$title	$timestamp	$username', threads=threads+1, posts=posts+$replycount, todayposts=todayposts+$replycount WHERE fid='$cid'");
	
	$dt=date("yymd");
	$db->query("UPDATE {$tablepre}common_stat SET `thread`=`thread`+1 WHERE daytime='$dt'");
	$db->query("UPDATE {$tablepre}forum_thread SET lastposter='$username', lastpost='$timestamp', replies=replies+$replycount WHERE tid='$tid'");
	$db->query("UPDATE LOW_PRIORITY {$tablepre}forum_thread SET views=views+$hits WHERE tid='$tid'");
	
	
	exit("sucess");
	
}else
{
	echo "<select name='list'>";
	echo maketree($cates,0,'');
	echo '</select>';
}
/****自己添加的函数*****/
function getattachtableid($tid) {
	$tid = (string)$tid;
	return intval($tid{strlen($tid)-1});
}

function getattachtablebytid($tid) {
	return 'forum_attachment_'.getattachtableid($tid);
}
/***生成目录的一个遍历算法***/
function maketree($ar,$id,$pre)
{
	$ids='';
	foreach($ar as $k=>$v){
		$pid=$v['pid'];
		$cname=$v['cname'];
		$cid=$v['cid'];
		if($pid==$id)
		{
			$ids.="<option value='$cid'>{$pre}{$cname}</option>";
			foreach($ar as $kk=>$vv)
			{
				$pp=$vv['pid'];
				if($pp==$cid)
				{ 
					$ids.=maketree($ar,$cid,$pre."&nbsp;&nbsp;");
					break;
				}
			}
		}
	}
	return $ids;
}

/****************************以下为公共类库及函数库******************************/
function daddslashes($string, $force = 0) {
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if(!MAGIC_QUOTES_GPC || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = daddslashes($val, $force);
			}
		} else {
			$string = addslashes($string);
		}
	}
	return $string;
}


/*当前为数据库操作类库*/
class db {

	var $mlink;

	function db($dbhost, $dbuser, $dbpw, $dbname = '',$charset='gbk',$dbcharset='gbk', $pconnect=0){
		if($pconnect){
			if(!$this->mlink = @mysql_pconnect($dbhost, $dbuser, $dbpw)){
				$this->halt('Can not connect to MySQL');
			}
		} else {
			if(!$this->mlink = @mysql_connect($dbhost, $dbuser, $dbpw)){
				$this->halt('Can not connect to MySQL');
			}
		}
		if($this->version()>'4.1'){
			if('utf-8'==strtolower($dbcharset)){
				$dbcharset='utf8';
			}
			if($dbcharset){
				mysql_query("SET character_set_connection=$dbcharset, character_set_results=$dbcharset, character_set_client=binary", $this->mlink);
			}
			if($charset){
				mysql_query("SET $charset", $this->mlink);
			}
			
			if($this->version() > '5.0.1'){
				mysql_query("SET sql_mode=''", $this->mlink);
			}
		}
		if($dbname){
			mysql_select_db($dbname, $this->mlink);
		}
	}

	function select_db($dbname){
		return mysql_select_db($dbname, $this->mlink);
	}
	
	function get_array($sql){
		$list = array();
		$query=$this->query($sql);
		while($row=$this->fetch_array($query)){
			$list[]=$row;
		}
		return $list;
	}
	
	function fetch_array($query, $result_type = MYSQL_ASSOC){
		return (is_resource($query))? mysql_fetch_array($query, $result_type) :false;
	}

	function result_first($sql){
		$query = $this->query($sql);
		return $this->result($query, 0);
	}

	function fetch_first($sql){
		$query = $this->query($sql);
		return $this->fetch_array($query);
	}
	
	
	function fetch_total($table,$where='1'){
		return $this->result_first("SELECT COUNT(*) num FROM ".DB_TABLEPRE."$table WHERE $where");
	}
	
	function query($sql, $type = ''){
		global $mquerynum;
		$func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ? 'mysql_unbuffered_query' : 'mysql_query';
		if(!($query = $func($sql, $this->mlink)) && $type != 'SILENT'){
			$this->halt("MySQL Query Error",'TRUE',$sql);
		}
		$mquerynum++;
		return $query;
	}

	function affected_rows(){
		return mysql_affected_rows($this->mlink);
	}

	function error(){
		return (($this->mlink) ? mysql_error($this->mlink) : mysql_error());
	}

	function errno(){
		return intval(($this->mlink) ? mysql_errno($this->mlink) : mysql_errno());
	}

	function result($query, $row){
		$query = @mysql_result($query, $row);
		return $query;
	}

	function num_rows($query){
		$query = mysql_num_rows($query);
		return $query;
	}

	function num_fields($query){
		return mysql_num_fields($query);
	}

	function free_result($query){
		return mysql_free_result($query);
	}

	function insert_id(){
		return ($id = mysql_insert_id($this->mlink)) >= 0 ? $id : $this->result($this->query('SELECT last_insert_id()'), 0);
	}

	function fetch_row($query){
		$query = mysql_fetch_row($query);
		return $query;
	}

	function fetch_fields($query){
		return mysql_fetch_field($query);
	}

	function version(){
		return mysql_get_server_info($this->mlink);
	}

	function close(){
		return mysql_close($this->mlink);
	}

	function halt($msg, $debug=true, $sql=''){
		@ini_set("date.timezone","Asia/Shanghai");
		$output .="<html>\n<head>\n";
		$output .="<meta http-equiv=\"Content-Type\" content=\"text/html; charset=".$charset."\">\n";
		$output .="<title>$msg</title>\n";
		$output .="</head>\n<body><table>";
		$output .="<b>MySql Error Info</b><table><tr><td width='100px'><b>Message</b></td><td>$msg</td></tr>\n";
		$output .="<tr><td><b>Time</b></td><td>".date("Y-m-d H:i:s")."<br /></td></tr>\n";
		$output .="<tr><td><b>Script</b></td><td> ".$_SERVER['PHP_SELF']."<br /></td></tr>\n\n";
		$output .="<tr><td><b>SQL</b></td><td> ".htmlspecialchars($sql)."<br />\n</td></tr><tr><td><b>Error</b></td><td>  ".$this->error()."</td></tr><br />\n";
		$output .="<tr><td><b>Errno.</b></td><td>  ".$this->errno()."</td></tr></table>";
		$output .="\n</body></html>";
		echo $output;
		exit();
	}
	
}
?>